package qqclient.service;

import qqcommon.Message;
import qqcommon.MessageType;
import qqcommon.User;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.InetAddress;
import java.net.Socket;

/**
 * 该类用于完成用户登入、注册等功能
 */
public class UserClientService {
    //可能会在其它地方使用User信息、Socket，因此做成成员属性
    private User user = new User();
    private Socket socket;

    //根据 userId 和 userPwd 到服务器验证该用户是否合法
    public boolean checkUser(String userId, String userPwd) {
        boolean checkLoop = false;
        //创建User对象
        user.setUserId(userId);
        user.setUserPwd(userPwd);
        //连接到服务器，发送user对象
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
            //得到ObjectOutputStream对象
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            oos.writeObject(user);//发送User对象

            //读取从服务的回复的Message对象
            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Message msg = (Message) ois.readObject();

            if (msg.getMesType().equals(MessageType.MESSAGE_LOGIN_SUCCEED)) {//登入成功

                //创建一个和服务器端保持通信的线程，创建一个线程类 ClientConnectServerThread
                ClientConnectServerThread clientConnectServerThread =
                        new ClientConnectServerThread(socket);
                //启动客户端的线程
                clientConnectServerThread.start();
                //将线程放入到集合管理
                ManageClientConnectServerThread.addClientConnectServerThread(userId,
                        clientConnectServerThread);
                checkLoop = true;

            } else {//关闭socket
                socket.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return checkLoop;
    }

    //向服务器端请求在线用户列表
    public void onlineFriendList() {
        //发送一个Message,MESSAGE_GET_ONLINE_FRIEND
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_GET_ONLINE_FRIEND);
        message.setSender(user.getUserId());
        //发送到服务器
        //得到当前线程的Socket 对应的 ObjectOutputStream 对象
        try {
            ObjectOutputStream oos = new ObjectOutputStream(
                    ManageClientConnectServerThread.
                            getClientConnectServerThread(
                                    user.getUserId()).getSocket().getOutputStream());
            oos.writeObject(message);//发送一个Message对象，向服务的请求在线用户列表
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //编写方法，退出客户端，并给服务器端发送一个退出系统的message对象
    public void logout() {
        Message message = new Message();
        message.setMesType(MessageType.MESSAGE_CLIENT_EXIT);
        message.setSender(user.getUserId());//一定要指定我是哪个客户端用户

        //发送message
        try {
            //ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            ObjectOutputStream oos = new ObjectOutputStream(
                    ManageClientConnectServerThread.
                            getClientConnectServerThread(
                                    user.getUserId()).getSocket().getOutputStream());
            oos.writeObject(message);
            System.out.println(user.getUserId() + " 退出系统");
            System.exit(0);//正常结束进程
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //新增用户注册方法
    public boolean registerUser(String userId, String userPwd) {
        boolean isRegistered = false;
        user.setUserId(userId);
        user.setUserPwd(userPwd);
        try {
            socket = new Socket(InetAddress.getByName("127.0.0.1"), 9999);
            ObjectOutputStream oos = new ObjectOutputStream(socket.getOutputStream());
            Message regMessage = new Message();
            regMessage.setMesType(MessageType.MESSAGE_REGISTER);
            regMessage.setUser(user);
            oos.writeObject(regMessage);

            ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
            Message response = (Message) ois.readObject();

            if (response.getMesType().equals(MessageType.MESSAGE_REGISTER_SUCCEED)) {
                System.out.println("注册成功，请登录！");
                isRegistered = true;
            } else if (response.getMesType().equals(MessageType.MESSAGE_REGISTER_FAIL)) {
                System.out.println("注册失败，用户名已存在！");
            }
            socket.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return isRegistered;
    }
}
